<template>
  <el-dialog :title="title" v-model="open" :width="getWidth()" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px"
      v-if="props.rightMenuData.param == 'createChild'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级部门" prop="parentId">
            <el-tree-select v-model="form.parentId" :data="deptOptions"
              :props="{ value: 'id', label: 'deptName', children: 'children' }" value-key="id" placeholder="选择上级部门"
              check-strictly filterable />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="部门名称" prop="title">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="11">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="11">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="11">
          <el-form-item label="部门状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px"
      v-else-if="props.rightMenuData.param == 'rename'">
      <el-row>
        <el-col :span="11">
          <el-form-item label="部门名称" prop="title">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px"
      v-else-if="props.rightMenuData.param == 'changeCompany'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级部门" prop="parentId">
            <el-tree-select v-model="form.parentId" :data="deptOptions"
              :props="{ value: 'id', label: 'deptName', children: 'children' }" value-key="id" placeholder="选择上级部门"
              check-strictly filterable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <updateInfo v-else-if="props.rightMenuData.param == 'addEquip'" :showWhich="'add'" :form="form"
      :sel_option="sel_option" ref="formInfo">
    </updateInfo>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px"
      v-else-if="props.rightMenuData.param == 'changeEquip'">
      <el-row>
        <el-col :span="11">
          <el-form-item label="上级部门" prop="companyId">
            <el-tree-select v-model="form.companyId" :data="deptOptions"
              :props="{ value: 'id', label: 'deptName', children: 'children' }" value-key="id" placeholder="选择上级部门"
              check-strictly filterable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <virtualTable v-else-if="props.rightMenuData.param == 'bindRules'" :columns="showColumns" :data="tableData"
      ref="v2Table" style="width:100%;height:500px">
      <template #rowItem="{ column, rowData, rowIndex }">
        <span v-if="column.key === 'index'">{{ rowIndex + 1 }}</span>
        <span v-else-if="column.key === 'operation'">
          <div @click="showAlarmDetail(rowData)" class="other-btn">
            查看详情
          </div>
        </span>
        <span v-else>{{ rowData[column.key] }}</span>
      </template>
    </virtualTable>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import request from "@/utils/request"
import virtualTable from "@/components/virtualTable"
import { addEquipmentManagement } from "@/api/comlbs/equipmentManagement";
const formInfo = ref(null);
import updateInfo from '../../comlbs/equipmentManagement/updateInfo'
import { listDept, addDept, updateDept, listDeptExcludeChild, treeDept } from "@/api/system/dept";
const props = defineProps({
  rightMenuData: { type: Object },
  refreshMapData: { type: Function },
  popTrackClick: { type: Function },
});
const title = ref("");
const { proxy } = getCurrentInstance();
const form = ref({});
const open = ref(false);
const rules = ref({});
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm("formRef");
}

const sel_option = ref({});
sel_option.value = proxy.useDict.apply(proxy, ["accountStatus", "objType", "checkStatus", "deviceModel", "channels"]);
proxy.setDataByDictType(sel_option.value, 'sys_user_sex', 'ownerSex');
treeDept().then(res => {
  sel_option.value.companyId = res.data
})

const tableData = ref([]);
const showColumns = ref([
  { key: "index", title: "序号", width: 60 },
  { key: "name", title: "规则名称", width: 160 },
  { key: "ruleAttr", title: "规则属性", width: null },
  { key: "createTime", title: "创建时间", width: 160 },
  { key: "operation", title: "操作", width: 100 },
]);
function getWidth() {
  return {
    "createChild": "800px",
    "rename": "600px",
    "addEquip": "800px",
    "changeCompany": "600px",
    "changeEquip": "600px",
    "bindRules": "800px",
  }[props.rightMenuData.param]
}
watch(() => props.rightMenuData, ({ param, data }) => {
  if (param) {
    switch (param) {
      case "createChild": //创建公司子节点
        handleCompanyAdd(data);
        break
      case "rename": //重命名
        handleCompanyUpdate(data);
        break
      case "addEquip": //新增设备
        handleAddEquip(data);
        break
      case "changeCompany": //迁移节点
        handleCompanyUpdate(data);
        break
      case "changeEquip": //迁移设备
        handleChangeEquip(data);
        break
      case "bindRules": //已绑规则
        handleBindRules(data);
        break
    }
    open.value = true;
  }
})
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


//设备相关
function handleAddEquip(row) {
  reset();
  title.value = "添加设备";
  form.value.companyId = row.id;
}
function handleBindRules(row) {
  title.value = "设备已绑定规则";
  request({
    url: "/comlbs/alarmRulePersonVehicle/binding/list",
    method: 'get',
    params: {
      objectId: row.objectId
    }
  }).then(res => {
    tableData.value = res.data;
  })
}
function handleChangeEquip(row) {
  title.value = "设备迁移";
  form.value.companyId = row.companyId;
  // 复用的接口，所以这里是数组
  form.value.ids = [row.equipmentId];
  rules.value = {
    companyId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  }
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "id");
  });
}
function showAlarmDetail(row) {

}

//公司相关
const deptOptions = ref([]);
/** 新增按钮操作 */
function handleCompanyAdd(row) {
  reset();
  listDept().then(response => {
    deptOptions.value = [{ deptName: '平台设备', id: '0', children: proxy.handleTree(response.data, "id") }];
  });
  if (row != undefined) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  title.value = "添加部门";
  rules.value = {
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  }
}
/** 修改按钮操作 */
function handleCompanyUpdate(row) {
  reset();
  listDeptExcludeChild(row.id).then(response => {
    deptOptions.value = [{ deptName: '平台设备', id: '0', children: proxy.handleTree(response.data, "id") }];
  });
  form.value = row;
  form.value.shortName = row.deptName;
  title.value = "修改部门";
  rules.value = {
    deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  }
}


/** 提交按钮 */
async function submitForm() {
  switch (props.rightMenuData.param) {
    case "createChild": //创建公司子节点
      proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          addDept(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            proxy.refreshMapData();
          });
        }
      });
      break
    case "rename": //重命名
      form.value.shortName = form.value.deptName
      proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          updateDept(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            proxy.refreshMapData();
          });
        }
      });
      break
    case "addEquip": //新增设备
      let _bool = await formInfo.value.validate();
      if (!_bool) return
      let _updateInfo = formInfo.value.updateInfo;
      let supervisionInfo = formInfo.value.supervisionInfo
      let driverInfo = formInfo.value.driverInfo
      let myUploadPic = formInfo.value.myUploadPic
      let driverUploadPic = formInfo.value.driverUploadPic
      // 不选监管类型时，将监管信息置空
      if (!_updateInfo.objType && _updateInfo.objType !== 0) {
        supervisionInfo = {}
        driverInfo = {}
      }
      let data = {
        deviceId: _updateInfo.deviceId,
        companyId: _updateInfo.companyId,
        deviceModel: _updateInfo.deviceModel,
        simId: _updateInfo.simId ?? '',
        objType: _updateInfo.objType,
        channels: '', // 视频接入
        remark: _updateInfo.remark,
        objIcon: '', // 设备图标
        numberPlate: supervisionInfo.numberPlate?.numberPlate || supervisionInfo.numberPlate,
        vehicleColor: supervisionInfo.vehicleColor,
        vehiclePic: [],  // 图片附件
        vehicleModel: supervisionInfo.vehicleModel,
        vehicleId: supervisionInfo.vehicleId,
        ageVehicle: supervisionInfo.ageVehicle,
        ownerSex: supervisionInfo.ownerSex,
        contactNumberVehicle: supervisionInfo.contactNumberVehicle,
        equipmentId: _updateInfo?.equipmentId,
        driverId: driverInfo.driverId, // 负责人id
        driverName: driverInfo.name?.name || driverInfo.name, // 负责人
        contactNumber: driverInfo.contactNumber,
        idCard: driverInfo.idCard, // 身份证号
        age: driverInfo.age,
        driverPic: [],  // 负责人图片附件
      }
      let channelArr = []
      if (_updateInfo.channels) {
        for (let i = 0; i < _updateInfo.channels; i++) {
          // 0表示没有选
          channelArr.push(sel_option.value.channels[i].chVal ?? 0)
        }
      }
      data.channels = channelArr.join(',')
      let imgArr = formInfo.value.supervisionImg[formInfo.value.supervisionArr[Number(_updateInfo.objType)]]
      if (imgArr && imgArr.length > 0) {
        imgArr.forEach(v => {
          if (v.indexOf('_active') > -1) data.objIcon = v.split('_')[0]
        })
      }
      // 监管对象的图片附件
      data.vehiclePic = await myUploadPic?.[0]?.uploadInfo();
      // 负责人的图片附件
      data.driverPic = await driverUploadPic?.[0]?.uploadInfo();
      if ((_updateInfo.objType || _updateInfo.objType === 0) && !data.objIcon) {  // 选监管类型时，设备图标必选
        proxy.$modal.msgWarning("请选择设备图标！");
        return
      }
      addEquipmentManagement(data).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
      });
      break
    case "changeCompany": //迁移节点
      proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          updateDept(form.value).then(response => {
            proxy.$modal.msgSuccess("迁移成功");
            open.value = false;
            proxy.refreshMapData();
          });
        }
      });
      break
    case "changeEquip": //迁移设备        
      proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          request({
            url: '/comlbs/equipmentManagement/batchUpdateCompany',
            method: 'post',
            data: form.value
          }).then(res => {
            proxy.$modal.msgSuccess("迁移成功");
            open.value = false;
            proxy.refreshMapData();
          })
        }
      });
      break
  }
}
</script>
<style lang='scss' scoped></style>